package com.evaluation.kexingcp.psycho.evaluation.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.kexingcp.admin.api.entity.SysDept;
import com.evaluation.kexingcp.admin.api.entity.SysUser;
import com.evaluation.kexingcp.admin.service.SysDeptService;
import com.evaluation.kexingcp.admin.service.SysUserService;
import com.evaluation.kexingcp.common.core.util.R;
import com.evaluation.kexingcp.common.excel.annotation.ResponseExcel;
import com.evaluation.kexingcp.common.log.annotation.SysLog;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationInquiryRecordsEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationTaskEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationWarningFollowEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.excels.BaseExcelExport;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationInquiryRecordsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 咨询记录
 *
 * @author pig
 * @date 2024-07-12 09:49:13
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/evaluationInquiryRecords" )
@Tag(description = "evaluationInquiryRecords" , name = "咨询记录管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class EvaluationInquiryRecordsController {

    private final EvaluationInquiryRecordsService evaluationInquiryRecordsService;
    private final SysUserService sysUserService;
    private final SysDeptService sysDeptService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param evaluationInquiryRecords 咨询记录
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('pigx_evaluationInquiryRecords_view')" )
    public R getEvaluationInquiryRecordsPage(@ParameterObject Page page, @ParameterObject EvaluationInquiryRecordsEntity evaluationInquiryRecords) {
        LambdaQueryWrapper<EvaluationInquiryRecordsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.isNull(EvaluationInquiryRecordsEntity::getPid);


        if (!Objects.isNull(evaluationInquiryRecords.getUsername())) {
            List<SysUser> users = sysUserService.list(Wrappers.lambdaQuery(SysUser.class).like(SysUser::getName, evaluationInquiryRecords.getUsername()));
            if (!users.isEmpty()) {
                wrapper.in(EvaluationInquiryRecordsEntity::getUserId, users.stream().map(SysUser::getUserId).toList());
            } else {
                return R.ok(Page.of(1,0,0));
            }
        }

        if (!Objects.isNull(evaluationInquiryRecords.getCompleted())) {
            wrapper.eq(EvaluationInquiryRecordsEntity::getCompleted, evaluationInquiryRecords.getCompleted());
        }

        IPage<EvaluationInquiryRecordsEntity> list = evaluationInquiryRecordsService.page(page, wrapper);
        list.convert(this::setRecords);

        return R.ok(list);
    }

    private EvaluationInquiryRecordsEntity setRecords(EvaluationInquiryRecordsEntity record) {
        List<EvaluationInquiryRecordsEntity> arrayList = new ArrayList<>();
        EvaluationInquiryRecordsEntity cloned = new EvaluationInquiryRecordsEntity();
        BeanUtils.copyProperties(record, cloned);
        arrayList.add(cloned);
        arrayList.addAll(evaluationInquiryRecordsService.list(
                Wrappers.lambdaQuery(EvaluationInquiryRecordsEntity.class)
                        .eq(EvaluationInquiryRecordsEntity::getPid, record.getId())
                        .orderByAsc(EvaluationInquiryRecordsEntity::getCreateTime)));

        record.setRecords(arrayList);

        SysUser user = sysUserService.getById(record.getUserId());
        if (user != null)
            user.setDeptList(sysDeptService.listParentDept(user.getDeptId()).stream().map(SysDept::getName).toList().reversed());
        record.setUser(user);
        return record;
    }


    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/list" )
    @PreAuthorize("@pms.hasPermission('pigx_evaluationInquiryRecords_view')" )
    public R list(@ParameterObject EvaluationInquiryRecordsEntity evaluationInquiryRecords) {
        LambdaQueryWrapper<EvaluationInquiryRecordsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.isNull(EvaluationInquiryRecordsEntity::getPid);
        wrapper.eq(EvaluationInquiryRecordsEntity::getCompleted, false);

        List<EvaluationInquiryRecordsEntity> list = evaluationInquiryRecordsService.list(wrapper);
        list = list.stream().peek(record -> {
            List<EvaluationInquiryRecordsEntity> arrayList = new ArrayList<>();
            EvaluationInquiryRecordsEntity cloned = new EvaluationInquiryRecordsEntity();
            BeanUtils.copyProperties(record, cloned);
            arrayList.add(cloned);
            arrayList.addAll(evaluationInquiryRecordsService.list(
                    Wrappers.lambdaQuery(EvaluationInquiryRecordsEntity.class)
                            .eq(EvaluationInquiryRecordsEntity::getPid, record.getId())
                            .orderByAsc(EvaluationInquiryRecordsEntity::getCreateTime)));
            record.setRecords(arrayList);
            SysUser user = sysUserService.getById(record.getUserId());
            if (user != null)
                user.setDeptList(sysDeptService.listParentDept(user.getDeptId()).stream().map(SysDept::getName).toList().reversed());
            record.setUser(user);
        }).toList();

        return R.ok(list);
    }


    /**
     * 通过id查询咨询记录
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('pigx_evaluationInquiryRecords_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        EvaluationInquiryRecordsEntity entity = evaluationInquiryRecordsService.getById(id);
        SysUser user = sysUserService.getById(entity.getUserId());
        user.setDeptList(sysDeptService.listParentDept(user.getDeptId()).stream().map(SysDept::getName).toList().reversed());
        entity.setUser(user);

        return R.ok(entity);
    }

    /**
     * 新增咨询记录
     * @param evaluationInquiryRecords 咨询记录
     * @return R
     */
    @Operation(summary = "新增咨询记录" , description = "新增咨询记录" )
    @SysLog("新增咨询记录" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('pigx_evaluationInquiryRecords_add')" )
    public R save(@RequestBody EvaluationInquiryRecordsEntity evaluationInquiryRecords) {
        if (evaluationInquiryRecords.getCompleted()) {
            EvaluationInquiryRecordsEntity entity = evaluationInquiryRecordsService.getById(evaluationInquiryRecords.getPid());
            entity.setCompleted(true);
            evaluationInquiryRecordsService.updateById(entity);
        }

        return R.ok(evaluationInquiryRecordsService.save(evaluationInquiryRecords));
    }

    /**
     * 修改咨询记录
     * @param evaluationInquiryRecords 咨询记录
     * @return R
     */
    @Operation(summary = "修改咨询记录" , description = "修改咨询记录" )
    @SysLog("修改咨询记录" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('pigx_evaluationInquiryRecords_edit')" )
    public R updateById(@RequestBody EvaluationInquiryRecordsEntity evaluationInquiryRecords) {
        return R.ok(evaluationInquiryRecordsService.updateById(evaluationInquiryRecords));
    }

    /**
     * 通过id删除咨询记录
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除咨询记录" , description = "通过id删除咨询记录" )
    @SysLog("通过id删除咨询记录" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('pigx_evaluationInquiryRecords_del')" )
    public R removeById(@RequestBody Long[] ids) {
        evaluationInquiryRecordsService
                .remove(Wrappers.lambdaQuery(EvaluationInquiryRecordsEntity.class).in(EvaluationInquiryRecordsEntity::getPid, ids));
        return R.ok(evaluationInquiryRecordsService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param evaluationInquiryRecords 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('pigx_evaluationInquiryRecords_export')" )
    public void export(HttpServletResponse response,EvaluationInquiryRecordsEntity evaluationInquiryRecords,Long[] ids) throws IOException {
        List<EvaluationInquiryRecordsEntity> data = evaluationInquiryRecordsService.list(Wrappers.lambdaQuery(evaluationInquiryRecords).isNull(EvaluationInquiryRecordsEntity::getPid).in(ArrayUtil.isNotEmpty(ids), EvaluationInquiryRecordsEntity::getId, ids));
        data = data.stream().map(this::setRecords).toList();
        EvaluationInquiryRecordsController.EvaluationInquiryRecordsExport export = new EvaluationInquiryRecordsController.EvaluationInquiryRecordsExport(response, List.of("姓名", "年龄", "性别", "内容", "咨询主题", "跟进状态", "组织/单位"));
        export.doExport(data);
    }

    public static class EvaluationInquiryRecordsExport extends BaseExcelExport<EvaluationInquiryRecordsEntity> {
        public EvaluationInquiryRecordsExport(HttpServletResponse response, List<String> title) {
            super(response, title);
        }

        @Override
        protected void writeData(List<EvaluationInquiryRecordsEntity> data) {
            // 写入数据
            XSSFRow row;
            XSSFCell cell;
            for (int i = 0; i < data.size(); i++) {
                row = sheet.createRow(i + 1);
                for (String t : title) {
                    int j = ListUtils.indexOf(title, s -> StringUtils.equalsIgnoreCase(t, s));
                    cell = row.createCell(j);
                    if (StringUtils.equalsIgnoreCase(t, "姓名")) {
                        if (data.get(i).getUser() != null) {
                            cell.setCellValue(data.get(i).getUser().getName());
                        } else {
                            cell.setCellValue("用户已被删除,请删除此记录");
                        }
                    } else if (StringUtils.equalsIgnoreCase(t, "年龄")) {
                        if (data.get(i).getUser() != null) {
                            cell.setCellValue(data.get(i).getUser().getAge());
                        } else {
                            cell.setCellValue("用户已被删除,请删除此记录");
                        }
                    } else if (StringUtils.equalsIgnoreCase(t, "性别")) {
                        if (data.get(i).getUser() != null) {
                            cell.setCellValue(data.get(i).getUser().getSex());
                        } else {
                            cell.setCellValue("用户已被删除,请删除此记录");
                        }
                    } else if (StringUtils.equalsIgnoreCase(t, "咨询主题")) {
                        cell.setCellValue(data.get(i).getInquiryTheme());
                    }  else if (StringUtils.equalsIgnoreCase(t, "跟进状态")) {
                        // 设置文字颜色为红色
                        XSSFCellStyle cellStyle = workbook.createCellStyle();
                        XSSFFont font = workbook.createFont();
                        if (data.get(i).getCompleted()) {
                            font.setColor(IndexedColors.BLUE.index);
                            cell.setCellValue("已完结");
                        } else {
                            font.setColor(IndexedColors.RED.index);
                            cell.setCellValue("未完结");
                        }
                        cellStyle.setFont(font);
                        cell.setCellStyle(cellStyle);
                    } else if (StringUtils.equalsIgnoreCase(t, "组织/单位")) {
                        if (data.get(i).getUser() != null){
                            cell.setCellValue(data.get(i).getUser().getDeptList().stream().reduce((s1, s2) -> s1 + "/" + s2).orElse(""));
                        } else {
                            cell.setCellValue("用户已被删除,请删除此记录");
                        }
                    } else if (StringUtils.equalsIgnoreCase(t, "内容")) {
                        if (!data.get(i).getRecords().isEmpty()) {
                            List<EvaluationInquiryRecordsEntity> records = data.get(i).getRecords();
                            StringBuilder sb = new StringBuilder();
                            for (int k = 0; k < records.size(); k++) {
                                sb.append("第").append(k + 1).append("次:").append(records.get(k).getInquiryReason()).append("\n");
                            }
                            cell.setCellValue(sb.toString());
                        }
                    }
                }
            }
        }
    }
}